import common.twitter_util as twitter_util
import logging
import pickle
import tweepy
from google.appengine.api import taskqueue
from google.appengine.api.taskqueue import Queue
from google.appengine.ext.webapp import RequestHandler, template
from google.appengine.ext import db
from handler.config import CONSUMER_KEY, CONSUMER_SECRET, CALLBACK
from model.system_key_value_pair import SystemKeyValuePair
from model.token import OAuthRequestToken


class PollerPage(RequestHandler):
    def get(self):
        poller_version = SystemKeyValuePair.get('poller')
        app_signed_in = True
        try:
            twitter_util.get_app_auth_handler(self.request.url)
        except:
            app_signed_in = False
        
        print template.render(
            'view/poller.html', 
            {'poller_version': poller_version.value,
             'app_signed_in': app_signed_in})

    def post(self):
        action = self.request.get('action', 'stop')
        version = self.__stop_current_poller()
        if action == 'restart':
            self.__start_new_poller(version)
        self.redirect('poller')
        
    def __stop_current_poller(self):
        poller_version = SystemKeyValuePair.get('poller')
        logging.info('Current poller version is %d.' 
                     % poller_version.value)
        poller_version.increment()
        logging.info('Stop current poller by '
                     'increasing poller version to %d.' 
                     % poller_version.value)
        return poller_version.value

    def __start_new_poller(self, version):
        skip_old_updates_from_post = self.request.get(
            "skip_old_updates", None)
        skip_old_updates = False
        if skip_old_updates_from_post:
            skip_old_updates = True
        taskqueue.add(url='/task/poller',
                      queue_name='poller', 
                      params={'skip_old_updates': skip_old_updates,
                              'poller_version': version})
        logging.info('Start new poller task, version:%d' % version)
        